package com.service.totalauth.controller;

import com.service.config.annotation.Distinct;
import com.service.config.utils.*;
import com.service.totalauth.dto.*;
import com.service.totalauth.entity.ManageInfo;
import com.service.totalauth.service.ManageInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

import static com.service.config.constant.Constant.*;
import static com.service.totalauth.util.TransformationIp.getRealIp;

/**
 * 管理人员表(ManageInfo)表控制层
 *
 * @author makejava
 * @since 2021-12-03 09:38:48
 */
@RestController
@RequestMapping("manageInfo")
@Api(value = "租户管理人员接口", tags = "租户管理人员接口")
public class ManageInfoController {
    @Resource
    private ManageInfoService manageInfoService;
    @Resource
    private RedisUtil redisUtil;
    /**
     * 统一登录
     *
     * @param
     * @return
     */
    @PostMapping(value = "auth",produces="application/json")
    @ApiOperation(value = "统一登录")
    @ResponseBody
    public Result loginManage(HttpServletRequest httpServletRequest,
                              @RequestBody LoginUserDto loginUserDto) throws Exception {
        HashMap map = new HashMap();
        if(loginUserDto.getAccount() == null || "".equals(loginUserDto.getAccount())
                || "".equals(loginUserDto.getPassword()) || loginUserDto.getPassword() == null){
            return Result.failure(10003,"用户名或密码为空");
        }
        map = manageInfoService.getToken(loginUserDto,httpServletRequest);
        if(map == null){
            return Result.failure(USER_NOT_FOUND,"用户不存在");
        }
        return Result.ok().setData(map);

    }
    /**
     * 用户标准注册
     *
     * @param
     * @return
     */
    @GetMapping(value = "getInfo",produces="application/json")
    @ApiOperation(value = "查找个人信息")
    @ResponseBody
    public Result getInfo(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 密码修改
                ManageInfo manageInfo = manageInfoService.queryById(userId);
                ManageInfoDto manageInfoDto = ModelMapperUtil.strictMap(manageInfo, ManageInfoDto.class);
                return Result.ok().setData(manageInfoDto);
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
    /**
     * 用户标准注册
     *
     * @param
     * @return
     */
    @PostMapping(value = "updateInfo",produces="application/json")
    @ApiOperation(value = "修改个人信息")
    @ResponseBody
    public Result updateInfo(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                           @RequestBody ManageInfoDto manageInfoDto) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 密码修改
                ManageInfo manageInfo = ModelMapperUtil.strictMap(manageInfoDto, ManageInfo.class);
                manageInfo.setId(userId);
                manageInfoService.update(manageInfo);
                return Result.ok();
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
    /**
     * 用户标准注册
     *
     * @param
     * @return
     */
    @PostMapping(value = "register",produces="application/json")
    @ApiOperation(value = "用户标准注册")
    @ResponseBody
    @Distinct
    public Result register(HttpServletRequest httpServletRequest,
                           @RequestBody UserInfoDto userInfoDto) throws Exception {
        if(userInfoDto.getUsername() == null || "".equals(userInfoDto.getUsername())
                || "".equals(userInfoDto.getPassword()) || userInfoDto.getPassword() == null){
            return Result.failure(USERNAME_OR_NOTFOUND,"用户名或密码为空,请重新输入");
        }
        String realIp = getRealIp(httpServletRequest);
        HashMap<Object,Object> map = new HashMap<>(16);
        ManageInfo register = manageInfoService.register(userInfoDto,realIp);
        if (register != null) {
            String token = UserTokenManager.generateToken(register.getId());
            map.put("Token",token);
            UserDto userDto = ModelMapperUtil.strictMap(userInfoDto, UserDto.class);
            userDto.setIp(realIp); // 来源ip
            userDto.setDate(new Date()); //登录时间
            redisUtil.setValue(token+register.getId(), JsonXMLUtils.obj2json(register)); // 存入缓存
            return Result.ok().setData(map);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
    /**
     * 用户简化注册
     *
     * @param
     * @return
     */
    @PostMapping(value = "simplifyRegister",produces="application/json")
    @ApiOperation(value = "用户简化注册")
    @ResponseBody
    //@Distinct
    public Result simplifyRegister(HttpServletRequest httpServletRequest,
                                   @RequestBody SimplifyUserInfoDto simplifyUserInfoDto) throws Exception {
        if(simplifyUserInfoDto.getApiUsername() == null || "".equals(simplifyUserInfoDto.getApiUsername())
                || "".equals(simplifyUserInfoDto.getApiPassword()) || simplifyUserInfoDto.getApiPassword() == null){
            return Result.failure(USERNAME_OR_NOTFOUND,"用户名或密码为空,请重新输入");
        }
        String realIp = getRealIp(httpServletRequest);
        return manageInfoService.simplifyRegister(simplifyUserInfoDto, realIp);
    }
    /**
     * 忘记密码/修改密码
     *
     * @param
     * @return
     */
    @PostMapping(value = "retrieve",produces="application/json")
    @ApiOperation(value = "忘记密码/修改密码")
    @ResponseBody
    public Result retrieve(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                           @RequestBody UserInfoDto userInfoDto) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 密码修改
                userInfoDto.setId(userId);
                manageInfoService.update(ModelMapperUtil.strictMap(userInfoDto, ManageInfo.class));
                Set<String> strings = redisUtil.redisLike(userId);
                clearCache(strings, redisUtil);
                return Result.ok();
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        ManageInfo userInfo = manageInfoService.queryByUserName(userInfoDto);
        if (userInfo == null) {
            return Result.failure(USER_INFO_IMPERFECT,"用户信息不完善请联系管理人员进行修正");
        }
        return Result.ok();
    }

    /**
     * 清除缓存
     * @param strings
     * @param redisUtil
     */
    public static void clearCache(Set<String> strings, RedisUtil redisUtil) {
        strings.stream().forEach(
                s -> {
                    String value = redisUtil.getValue(s);
                    try {
                        UserDto userDto1 = JsonXMLUtils.json2obj(value, UserDto.class);
                        userDto1.setOffTime(new Date());
                        long dateMin = DateUtil.getDateMin(DateUtil.datetoString(userDto1.getDate()), DateUtil.datetoString(new Date()));
                        userDto1.setOnlineTime(dateMin); // 在线时长
                        redisUtil.leftPush(USER_INFO_AI_FISH,JsonXMLUtils.obj2json(userDto1));
                        redisUtil.delete(s);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        );
    }

    /**
     * 找回密码
     *
     * @param
     * @return
     */
    @PostMapping(value = "verification",produces="application/json")
    @ApiOperation(value = "找回密码")
    @ResponseBody
    public Result retrieve(@RequestBody VerificationCodeDto verificationCodeDto) throws Exception {
        if (redisUtil.exist(verificationCodeDto.getCode())) {
            if (verificationCodeDto.getUsername() != null && !verificationCodeDto.getUsername().equals("")) {
                String value = redisUtil.getValue(verificationCodeDto.getCode());
                UserInfoDto userInfoDto =JsonXMLUtils.json2obj(value, UserInfoDto.class);
                if (verificationCodeDto.getUsername().equals(userInfoDto.getUsername())) {
                    ManageInfo userInfo = JsonXMLUtils.json2obj(value, ManageInfo.class);
                    userInfo.setPassword(verificationCodeDto.getPassword());
                    // 默认大屏服务修改密码
                    manageInfoService.update(ModelMapperUtil.strictMap(userInfoDto, ManageInfo.class));
                    redisUtil.delete(verificationCodeDto.getCode());
                    return Result.ok();
                }
                return Result.failure(USERNAME_DIFFERENT,"用户名不正确，请重新填写");
            }
            return Result.failure(USER_NOT_FOUND,"用户名不存在");
        }
        return Result.failure(CODE_INVALID,"验证码已失效，请重新获取");
    }




    /**
     * 用户注销
     *
     * @param
     * @return
     */
    @GetMapping(value = "loginOut",produces="application/json")
    @ApiOperation(value = "用户注销")
    @ResponseBody
    public Result loginOut(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken) throws Exception {
        System.out.println(cloudAuthToken);
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 缓存是否存在
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                userDto.setOffTime(new Date());
                userDto.setOnlineTime(DateUtil.getDateMin(DateUtil.datetoString(userDto.getDate()), DateUtil.datetoString(new Date())));
                ManageInfo userInfo = new ManageInfo();
                userInfo.setId(userId);
                userInfo.setIp(userDto.getIp());
                userInfo.setOnlineTime(userDto.getOnlineTime().intValue());
                userInfo.setOffTime(userDto.getOffTime());
                userInfo.setStatus(1);
                manageInfoService.update(userInfo);
                redisUtil.leftPush(USER_INFO_AI_FISH,JsonXMLUtils.obj2json(userDto));
                redisUtil.delete(cloudAuthToken+userId);
                return Result.ok();
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USER_NOT_LOGIN,"用户未登录");
    }
}
